import { defineStore } from "pinia";
import { ref } from "vue";
import {loginApi} from '@/api/login'


//创建pinia存储
//注意：仓库名user应该是唯一的函数名，尽量保持 “user+仓库名+store”的方法
export const useUserStore = defineStore('user', () => {
    //用户数据
    const userInfo=ref(JSON.parse(localStorage.getItem('userInfo')||'()'))
    //设置
    const setUserInfo=(payload)=>{
        userInfo.value=payload
        localStorage.setItem('userInfo',JSON.stringify(payload))
    }

    //登录状态
    const token=ref(localStorage.getItem('token')||null)
    //设置token
    const setToken=(payload)=>{
        token.value=payload
        localStorage.setItem('token',payload)
    }
    //登录
    const login=async(formData)=>{
        //登录
        const data=await loginApi(formData)
        //设置token
        setToken(data.token)
        //设置用户数据
        setUserInfo(data)
    }
    
    return {userInfo,token,login}
})